package com.cinc.ebc.mm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinc.ebc.mm.entity.MmPurchaseRequisition;
import com.cinc.ebc.mm.entity.MmPurchaseRequisitionDetail;
import com.cinc.ebc.mm.vo.MmPurchaseRequisitionDetailPage;
import com.cinc.ebc.mm.vo.MmPurchaseRequisitionPage;
import com.cinc.ebc.mm.model.MmPurchaseRequisitionDetailModel;
import com.cinc.ebc.mm.service.IMmPurchaseRequisitionDetailService;
import com.cinc.ebc.mm.service.IMmPurchaseRequisitionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 采购申请
 * @Author: jeecg-boot
 * @Date:   2022-03-20
 * @Version: V1.0
 */
@Api(tags="采购申请")
@RestController
@RequestMapping("/mm/purchaseRequisition")
@Slf4j
public class MmPurchaseRequisitionController {
	@Autowired
	private IMmPurchaseRequisitionService mmPurchaseRequisitionService;
	@Autowired
	private IMmPurchaseRequisitionDetailService mmPurchaseRequisitionDetailService;

	/**
	 * 分页列表查询
	 *
	 * @param mmPurchaseRequisition
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购申请-分页列表查询")
	@ApiOperation(value="采购申请-分页列表查询", notes="采购申请-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MmPurchaseRequisition mmPurchaseRequisition,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
		QueryWrapper<MmPurchaseRequisition> queryWrapper = QueryGenerator.initQueryWrapper(mmPurchaseRequisition, req.getParameterMap());
		Page<MmPurchaseRequisition> page = new Page<MmPurchaseRequisition>(pageNo, pageSize);
		IPage<MmPurchaseRequisition> pageList = mmPurchaseRequisitionService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 采购申请明细-分页列表查询
	  *
	  * @param mmPurchaseRequisitionDetailPage
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @PermissionData(pageComponent = "ebc/mm/MmPurchaseRequisitionDetailList")
	 @AutoLog(value = "采购申请明细-分页列表查询")
	 @ApiOperation(value="采购申请明细-分页列表查询", notes="采购申请明细-分页列表查询")
	 @GetMapping(value = "/pageDetailList")
	 public Result<?> queryPageDetailList(MmPurchaseRequisitionDetailPage mmPurchaseRequisitionDetailPage,
                                        @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                        HttpServletRequest req) {
		 IPage<MmPurchaseRequisitionDetailModel> page = new Page<>(pageNo, pageSize);
		 mmPurchaseRequisitionService.detailPage(page, mmPurchaseRequisitionDetailPage);
		 return Result.OK(page);
	 }

	 /**
	  * 采购申请明细-列表查询
	  *
	  * @param mmPurchaseRequisitionDetailPage
	  * @param req
	  * @return
	  */
	 @PermissionData(pageComponent = "ebc/mm/MmPurchaseRequisitionDetailList")
	 @AutoLog(value = "采购申请明细-列表查询")
	 @ApiOperation(value="采购申请明细-列表查询", notes="采购申请明细-列表查询")
	 @GetMapping(value = "/detailList")
	 public Result<?> queryDetailList(MmPurchaseRequisitionDetailPage mmPurchaseRequisitionDetailPage, HttpServletRequest req) {
		 List<MmPurchaseRequisitionDetailModel> resultList = mmPurchaseRequisitionService.detailList(mmPurchaseRequisitionDetailPage);
		 return Result.OK(resultList);
	 }

	/**
	 *   添加
	 *
	 * @param mmPurchaseRequisitionPage
	 * @return
	 */
	@AutoLog(value = "采购申请-添加")
	@ApiOperation(value="采购申请-添加", notes="采购申请-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody MmPurchaseRequisitionPage mmPurchaseRequisitionPage) {
		MmPurchaseRequisition mmPurchaseRequisition = new MmPurchaseRequisition();
		BeanUtils.copyProperties(mmPurchaseRequisitionPage, mmPurchaseRequisition);
		mmPurchaseRequisitionService.saveMain(mmPurchaseRequisition, mmPurchaseRequisitionPage.getMmPurchaseRequisitionDetailList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mmPurchaseRequisitionPage
	 * @return
	 */
	@AutoLog(value = "采购申请-编辑")
	@ApiOperation(value="采购申请-编辑", notes="采购申请-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody MmPurchaseRequisitionPage mmPurchaseRequisitionPage) {
		MmPurchaseRequisition mmPurchaseRequisition = new MmPurchaseRequisition();
		BeanUtils.copyProperties(mmPurchaseRequisitionPage, mmPurchaseRequisition);
		MmPurchaseRequisition mmPurchaseRequisitionEntity = mmPurchaseRequisitionService.getById(mmPurchaseRequisition.getId());
		if(mmPurchaseRequisitionEntity==null) {
			return Result.error("未找到对应数据");
		}
		mmPurchaseRequisitionService.updateMain(mmPurchaseRequisition, mmPurchaseRequisitionPage.getMmPurchaseRequisitionDetailList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购申请-通过id删除")
	@ApiOperation(value="采购申请-通过id删除", notes="采购申请-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		mmPurchaseRequisitionService.delMain(id);
		return Result.OK("删除成功!");
	}

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "采购申请明细-通过id删除")
	 @ApiOperation(value="采购申请明细-通过id删除", notes="采购申请明细-通过id删除")
	 @DeleteMapping(value = "/deleteDetail")
	 public Result<?> deleteDetail(@RequestParam(name="id",required=true) String id) throws Exception {
		 mmPurchaseRequisitionService.delDetail(id);
		 return Result.OK("删除成功!");
	 }

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购申请-批量删除")
	@ApiOperation(value="采购申请-批量删除", notes="采购申请-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mmPurchaseRequisitionService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	 /**
	  *  批量删除明细
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "采购申请明细-批量删除")
	 @ApiOperation(value="采购申请明细-批量删除", notes="采购申请明细-批量删除")
	 @DeleteMapping(value = "/deleteBatchDetail")
	 public Result<?> deleteBatchDetail(@RequestParam(name="ids",required=true) String ids) throws Exception {
		 this.mmPurchaseRequisitionService.delBatchDetail(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购申请-通过id查询")
	@ApiOperation(value="采购申请-通过id查询", notes="采购申请-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		MmPurchaseRequisition mmPurchaseRequisition = mmPurchaseRequisitionService.getById(id);
		if(mmPurchaseRequisition==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mmPurchaseRequisition);

	}

	/**
	 * 通过主表ID查询明细
	 *
	 * @param mainId
	 * @return
	 */
	@AutoLog(value = "采购申请明细通过主表ID查询")
	@ApiOperation(value="采购申请明细主表ID查询", notes="采购申请明细-通主表ID查询")
	@GetMapping(value = "/queryDetailListByMainId")
	public Result<?> queryDetailListByMainId(@RequestParam(name="mainId",required=false) String mainId) {
		List<MmPurchaseRequisitionDetail> mmPurchaseRequisitionDetailList = mmPurchaseRequisitionDetailService.selectByMainId(mainId);
		return Result.OK(mmPurchaseRequisitionDetailList);
	}

	 /**
	  * 通过主表ID查询明细
	  *
	  * @param mainId
	  * @return
	  */
	 @AutoLog(value = "采购申请明细通过主表ID查询")
	 @ApiOperation(value="采购申请明细主表ID查询", notes="采购申请明细-通主表ID查询")
	 @GetMapping(value = "/queryDetailPageListByMainId")
	 public Result<?> queryDetailPageListByMainId(@RequestParam(name="mainId",required=true) String mainId,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
	 	IPage<MmPurchaseRequisitionDetailModel> page = new Page<>(pageNo, pageSize);
		mmPurchaseRequisitionDetailService.selectAllPageByMainId(page, mainId);
		 return Result.OK(page);
	 }

	 /**
	  * 通过id查询
	  *
	  * @param mainIds
	  * @return
	  */
	 @AutoLog(value = "采购申请明细ID通过主表ID查询")
	 @ApiOperation(value="采购申请明细ID通过主表ID查询", notes="采购申请明细ID-通主表ID查询")
	 @GetMapping(value = "/queryDetailIdByMainId")
	 public Result<?> queryDetailIdByMainId(@RequestParam(name = "mainIds[]",required = true) List<String> mainIds) {
		 List<String> idList = mmPurchaseRequisitionDetailService.selectIdByMainId(mainIds);
		 return Result.OK(idList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param mmPurchaseRequisition
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MmPurchaseRequisition mmPurchaseRequisition) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<MmPurchaseRequisition> queryWrapper = QueryGenerator.initQueryWrapper(mmPurchaseRequisition, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<MmPurchaseRequisition> queryList = mmPurchaseRequisitionService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<MmPurchaseRequisition> mmPurchaseRequisitionList = new ArrayList<MmPurchaseRequisition>();
      if(oConvertUtils.isEmpty(selections)) {
          mmPurchaseRequisitionList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          mmPurchaseRequisitionList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<MmPurchaseRequisitionPage> pageList = new ArrayList<MmPurchaseRequisitionPage>();
      for (MmPurchaseRequisition main : mmPurchaseRequisitionList) {
          MmPurchaseRequisitionPage vo = new MmPurchaseRequisitionPage();
          BeanUtils.copyProperties(main, vo);
          List<MmPurchaseRequisitionDetail> mmPurchaseRequisitionDetailList = mmPurchaseRequisitionDetailService.selectByMainId(main.getId());
          vo.setMmPurchaseRequisitionDetailList(mmPurchaseRequisitionDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "采购申请列表");
      mv.addObject(NormalExcelConstants.CLASS, MmPurchaseRequisitionPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购申请数据", "导出人:"+sysUser.getRealname(), "采购申请"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<MmPurchaseRequisitionPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MmPurchaseRequisitionPage.class, params);
              for (MmPurchaseRequisitionPage page : list) {
                  MmPurchaseRequisition po = new MmPurchaseRequisition();
                  BeanUtils.copyProperties(page, po);
                  mmPurchaseRequisitionService.saveMain(po, page.getMmPurchaseRequisitionDetailList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
